﻿using System;
using System.Collections.Generic;
using System.Text;
using RayD.Repository.Entites.SystemModule;
using RayD.Core;
using RayD.Repository;
using Dapper;
using System.Data;
using System.Linq;
using RayD.Repository.Core;

namespace RayD.App.SystemModule
{
    public class ModuleApp
    {

        #region 构造函数注入
        private IRepository BaseRepository;
        public ModuleApp(IRepository repository)
        {
            this.BaseRepository = repository;
        }
        #endregion

        #region 获取数据 - 模块功能
        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="queryJson">查询条件</param>
        /// <returns></returns>
        public IEnumerable<ModuleEntity> GetModuleList(string queryJson)
        {
            var expression = LinqExtensions.True<ModuleEntity>();

            var queryParam = queryJson.ToJObject();
            if (!queryParam["B_FullName"].IsEmpty())
            {
                expression = expression.And(c => c.B_FullName.Contains(queryParam["B_FullName"].ToString()));
            }
            if (!queryParam["B_EnCode"].IsEmpty())
            {
                expression = expression.And(c => c.B_EnCode.Contains(queryParam["B_EnCode"].ToString()));
            }
            if (!queryParam["B_CreateDate"].IsEmpty())
            {
                expression = expression.And(c => c.B_CreateDate >= queryParam["B_CreateDate"][0].ToDate() && c.B_CreateDate <= queryParam["B_CreateDate"][1].ToDate());
            }
            return BaseRepository.IQueryable(expression).OrderBy(c => c.B_SortCode);
        }
        /// <summary>
        /// 获取分页列表数据
        /// </summary>
        /// <param name="queryJson">查询条件</param>
        /// <param name="pagination">分页参数</param>
        /// <returns></returns>
        public IEnumerable<ModuleEntity> GetPageList(string queryJson, Pagination pagination)
        {
            var expression = LinqExtensions.True<ModuleEntity>();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["B_FullName"].IsEmpty())
            {
                expression = expression.And(c => c.B_FullName.Contains(queryParam["B_FullName"].ToString()));
            }
            if (!queryParam["B_EnCode"].IsEmpty())
            {
                expression = expression.And(c => c.B_EnCode.Contains(queryParam["B_EnCode"].ToString()));
            }
            if (!queryParam["B_CreateDate"].IsEmpty())
            {
                expression = expression.And(c => c.B_CreateDate >= queryParam["B_CreateDate"][0].ToDate() && c.B_CreateDate <= queryParam["B_CreateDate"][1].ToDate());
            }
            var list = this.BaseRepository.IQueryable(expression)
                        .OrderBy(pagination.sidx, pagination.sord)
                        .ToTree();
            /***********************分页处理*********************/
            var rowsData = list.Skip(pagination.pageSize * (pagination.currentPage - 1)).Take(pagination.pageSize);
            pagination.records = list.Count();

            return rowsData;
        }
        /// <summary>
        /// 获取树型列表数据
        /// </summary>
        /// <param name="queryJson">查询条件</param>
        /// <returns></returns>
        [Caching]
        public virtual List<ModuleEntity> GetTreeList(string queryJson)
        {
            var expression = LinqExtensions.True<ModuleEntity>();
            var queryParam = queryJson.ToJObject();
            expression = expression.And(c => c.B_EnabledMark == EnabledMark.Enabled);
            return this.BaseRepository
                .IQueryable(expression)
                .OrderBy(c => c.B_SortCode)
                .ToTree()
                .ToList();
        }
        /// <summary>
        /// 根据URL获取模块功能
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [Caching]
        public virtual ModuleEntity GetModuleByUrl(string url)
        {
            return BaseRepository.FindEntity<ModuleEntity>(c => c.B_EnabledMark.Equals(EnabledMark.Enabled) && c.B_UrlAddress.Equals(url));
        }
        #endregion

        #region 获取数据 - 模块按钮
        /// <summary>
        /// 获取按钮列表数据
        /// </summary>
        /// <param name="moduleId">模块Id</param>
        /// <returns></returns>
        [Caching]
        public virtual List<ModuleButtonEntity> GetButtonList(string moduleId)
        {
            return BaseRepository
                .FindList<ModuleButtonEntity>(c => c.B_ModuleId == moduleId)
                .OrderBy(c => c.B_SortCode)
                .ToList();
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存实体(新增,编辑)
        /// </summary>
        /// <param name="moduleEntity">模块实体</param>
        /// <param name="moduleButtonList">模块按钮实体集合</param>
        /// <returns></returns>
        [RemoveCache("RayD_AuthorizeApp")]
        public virtual (bool, string) SaveForm(ModuleEntity moduleEntity, List<ModuleButtonEntity> moduleButtonList)
        {
            //字段验重
            if (ValidateExist(moduleEntity.B_ModuleId, "B_FullName", moduleEntity.B_FullName)) return (false, "模块名称已存在！");
            if (ValidateExist(moduleEntity.B_ModuleId, "B_EnCode", moduleEntity.B_EnCode)) return (false, "模块编码已存在！");
            var db = BaseRepository.BeginTrans();
            try
            {
                if (!moduleEntity.B_ModuleId.IsEmpty())
                {
                    //编辑(Null、主键不会更改)
                    moduleEntity.Modify();
                    db.Update(moduleEntity);
                    //删除模块按钮
                    db.Delete<ModuleButtonEntity>(c => c.B_ModuleId.Equals(moduleEntity.B_ModuleId));
                }
                else
                {
                    //新增
                    moduleEntity.Create();
                    db.Insert(moduleEntity);
                }

                //模块功能
                int i = 0;
                foreach (var moduleButton in moduleButtonList)
                {
                    moduleButton.Create();
                    moduleButton.B_ModuleId = moduleEntity.B_ModuleId;
                    moduleButton.B_SortCode = i;
                    db.Insert(moduleButton);
                    ++i;
                }
                db.Commit();
                return (true, "保存成功！");
            }
            catch (Exception)
            {
                db.Rollback();
                throw;
            }
        }
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="formEntity"></param>
        /// <returns></returns>
        [RemoveCache("RayD_AuthorizeApp")]
        public virtual (bool, string) DeleteForm(ModuleEntity formEntity)
        {
            var db = BaseRepository.BeginTrans();
            try
            {
                db.Delete(formEntity);
                //删除模块按钮
                db.Delete<ModuleButtonEntity>(c => c.B_ModuleId.Equals(formEntity.B_ModuleId));
                db.Commit();
                return (true, "删除成功！");
            }
            catch (Exception)
            {
                db.Rollback();
                throw;
            }
        }
        /// <summary>
        /// 更改状态
        /// </summary>
        /// <param name="formEntity"></param>
        /// <returns></returns>
        [RemoveCache("RayD_AuthorizeApp")]
        public virtual (bool, string) ChangeState(ModuleEntity formEntity)
        {
            int res = 0;
            if (!formEntity.B_ModuleId.IsEmpty())
            {
                res = this.BaseRepository.Update(new ModuleEntity() { B_ModuleId = formEntity.B_ModuleId, B_EnabledMark = formEntity.B_EnabledMark });
            }
            if (res > 0)
            {
                return (true, "更改成功！");
            }
            else
            {
                return (false, "更改失败！");
            }
        }
        #endregion

        #region 数据验证
        /// <summary>
        /// 验证字段值是否存在
        /// </summary>
        /// <param name="id">实体主键</param>
        /// <param name="field">字段名</param>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        public bool ValidateExist(string id, string field, string value)
        {
            var expression = LinqExtensions.True<ModuleEntity>();
            if (!string.IsNullOrEmpty(id))
            {
                expression = expression.And(t => t.B_ModuleId != id);
            }
            return this.BaseRepository.IQueryable(expression).Exist(field, value);
        }
        #endregion
    }
}
